﻿using System.Collections.Generic;
using System.IO;

namespace Streambolics
{
    /// <summary>
    ///     A computing module that triggers an action each time a given file is changed.
    /// </summary>

    public abstract class FileMonitor : TriggeredComputingModule
    {
        private string _FileName;
        private FileSystemWatcher _Watcher;

        public FileMonitor (string aFileName)
        {
            _FileName = aFileName;
        }

        public string DirectoryName
        {
            get
            {
                return _FileName.BeforeLast ("\\");
            }
        }

        public string FileName
        {
            get
            {
                return _FileName;
            }
        }

        protected override void DoStart ()
        {
            _Watcher = new FileSystemWatcher (DirectoryName);
            _Watcher.Changed += new FileSystemEventHandler (_Watcher_Changed);
            base.DoStart ();
        }

        protected override void DoStop ()
        {
            if (_Watcher != null)
            {
                _Watcher.Changed -= new FileSystemEventHandler (_Watcher_Changed);
                _Watcher.Dispose ();
                _Watcher = null;
            }
            base.DoStop ();
        }

        void _Watcher_Changed (object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Changed && e.FullPath.ToLower () == _FileName.ToLower ())
            {
                Trigger ();
            }
        }

        public IEnumerable<string> FileLines
        {
            get
            {
                return File.ReadAllLines (_FileName);
            }
        }

        public override string ArgumentsText
        {
            get
            {
                return _FileName;
            }
        }
    }
}
